<script lang="ts" setup>
import {onBeforeMount, PropType, ref} from 'vue'
import dDialog from '@/components/dDialog/dDialog.vue'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import operation from '@/components/dTable/components/operation.vue'
import {HeaderData, Operation as Oper, RowOperbuttons} from '@/components/dTable/dTable'
import {SearchButton} from '@/components/dTable/dHeader'
import {TransferController} from '@/util/transfer'
import {ColorRed, ColorTheme} from '@/api/config'
import {AddItemGroupList, GetAddItemGroup, getAddItemGroup, RegisterItemGroups, saveAddItemGroup, Situation} from '@/api/publicHealthExamination/physicalExaminationRegister'
import {ElMessage} from 'element-plus'

//是否显示
const props = defineProps({
  //显示
  showDialog: {
    type: Boolean,
    required: true
  },
  // 套餐id
  packageId: {
    type: String,
    required: true
  },
  // 体检登记id
  checkupRegisterId: {
    type: String,
    required: true
  },
  // 是否医院内网环境
  situation: {
    type: Boolean,
    required: true
  },
  // 体检套餐里面的项目组合列表，用于排除可选项目组合
  packageItemList: {
    type: Array as PropType<Array<RegisterItemGroups>>,
    required: true,
    defult: () => []
  },
  // 已选加项项目组合，用于回显
  selectedItemList: {
    type: Array as PropType<Array<RegisterItemGroups>>,
    required: true,
    defult: () => []
  }
})

const emits = defineEmits(['close', 'confirm', 'refresh'])

//穿梭控制器
let transfeController: TransferController<AddItemGroupList, AddItemGroupList> | null = null

// 已选项目组合
const selectedItemsData = ref<Array<AddItemGroupList & {oper: Array<Oper>}>>([])
// 已选项目组合数据暂存
const selectedItemsDataCache = ref<Array<AddItemGroupList & {oper: Array<Oper>}>>([])
const selectedItemsTableHeaderData = ref<Array<HeaderData>>([
  {
    prop: 'itemGroupCode',
    label: '项目组合编码',
    columnType: 'text',
    align: 'left',
    'min-width': '100'
  },
  {
    prop: 'itemGroupName',
    label: '项目组合名称',
    columnType: 'text',
    align: 'left',
    'min-width': '150'
  },
  {
    prop: 'price',
    label: '单价(元)',
    columnType: 'text',
    align: 'left',
    'min-width': '100'
  },
  {
    prop: 'oper',
    label: '操作',
    columnType: 'slot',
    align: 'center',
    width: '70',
    fixed: 'right'
  }
])

// 获取列表数据loading
const showSelectedItemsLoading = ref<boolean>(false)

const selectedItemsSearchButtons = ref<Array<SearchButton>>([
  {
    type: 'inputsearch',
    width: 320,
    value: '',
    placeholder: '搜索项目组合编码/项目组合名称'
  }
])

const selectedItemsRowOper: Array<Oper> = [
  {
    code: 'deletet',
    label: '移除',
    iconConfig: {
      icon: 'common-swap-reduce',
      type: 'custom',
      color: ColorRed,
      size: 20
    }
  }
]

// 可选项目组合
const optionalItemsData = ref<Array<AddItemGroupList & {oper: Array<Oper>}>>([])
// 可选项目组合数据缓存
const optionalItemsDataCache = ref<Array<AddItemGroupList & {oper: Array<Oper>}>>([])
const optionalItemsTableHeaderData = ref<Array<HeaderData>>([
  {
    prop: 'itemGroupCode',
    label: '项目组合编码',
    columnType: 'text',
    align: 'left',
    'min-width': '100'
  },
  {
    prop: 'itemGroupName',
    label: '项目组合名称',
    columnType: 'text',
    align: 'left',
    'min-width': '150'
  },
  {
    prop: 'price',
    label: '单价(元)',
    columnType: 'text',
    align: 'left',
    'min-width': '100'
  },
  {
    prop: 'oper',
    label: '操作',
    columnType: 'slot',
    align: 'center',
    width: '70',
    fixed: 'right'
  }
])

//可选项目组合搜索按钮配置
const optionalItemsSearchButtons = ref<Array<SearchButton>>([
  {
    type: 'inputsearch',
    width: 320,
    value: '',
    placeholder: '搜索项目组合编码/项目组合名称'
  }
])

const optionalItemsRowOper: Array<Oper> = [
  {
    code: 'append',
    label: '添加',
    iconConfig: {
      icon: 'common-swap-add',
      type: 'custom',
      color: ColorTheme,
      size: 20
    }
  }
]

// 表格加载状态
const showOptionalItemsLoading = ref<boolean>(false)

//更新左边数据
const updataLeftData = () => {
  if (transfeController) {
    const leftData = transfeController.getShowLeftData()
    const data: Array<AddItemGroupList & RowOperbuttons> = []
    leftData.forEach((item) => {
      data.push({
        ...item,
        oper: props.selectedItemList.some((packageItem) => {
          return item.itemGroupCode === packageItem.itemGroupCode
        })
          ? []
          : selectedItemsRowOper
      })
    })
    selectedItemsData.value = data
    selectedItemsDataCache.value = [...data] // 缓存数据，用于搜索还原和提交
  }
}

//更新右边数据
const updataRightData = () => {
  if (transfeController) {
    const rightData = transfeController.getShowRightData()
    const data: Array<AddItemGroupList & RowOperbuttons> = []
    rightData.forEach((item) => {
      data.push({
        ...item,
        oper: props.packageItemList.some((packageItem) => {
          return item.itemGroupCode === packageItem.itemGroupCode
        })
          ? []
          : optionalItemsRowOper // 判断套餐里面是否包含该项目
      })
    })
    optionalItemsData.value = data
    optionalItemsDataCache.value = [...data] // 缓存数据，用于搜索还原
  }
}

/**
 * @description: 列表行样式
 * @param {*} row
 * @return {*}
 */
const tableRowClassName = ({row}: {row: AddItemGroupList & RowOperbuttons}) => {
  if (row.oper.length === 0) {
    return 'disabled-row'
  } else {
    return ''
  }
}

//清除表格数据
const clearData = () => {
  if (transfeController) {
    transfeController.changeLeftData([])
    transfeController.changeRightData([])
    updataLeftData()
    updataRightData()
  }
}

/**
 * @description: 前端筛选数据
 * @return {*}
 */
const fuzzyQuery = (list: Array<AddItemGroupList & RowOperbuttons>, keyWord?: string): Array<AddItemGroupList & RowOperbuttons> => {
  if (!keyWord) {
    return list
  }
  let arr: Array<AddItemGroupList & RowOperbuttons> = list
  keyWord &&
    (arr = arr.filter((item) => {
      return item['itemGroupCode'].toLowerCase().indexOf(keyWord.toLowerCase()) !== -1 || item['itemGroupName'].toLowerCase().indexOf(keyWord.toLowerCase()) !== -1
    }))
  return arr
}

/**
 * @description: 检索已选项目组合
 * @return {*}
 */
const selectedItemsSubmit = () => {
  let keywords = ''
  const item = selectedItemsSearchButtons.value[0]
  if (item && item.type === 'inputsearch') {
    keywords = item.value ? item.value : ''
  }
  // 关键词过滤的数据
  selectedItemsData.value = [...new Set(fuzzyQuery(selectedItemsDataCache.value, keywords))]
}

/**
 * @description: 检索可选项目组合
 * @return {*}
 */
const optionalItemsSubmit = () => {
  let keywords = ''
  const item = optionalItemsSearchButtons.value[0]
  if (item && item.type === 'inputsearch') {
    keywords = item.value ? item.value : ''
  }
  // 关键词过滤的数据
  optionalItemsData.value = [...new Set(fuzzyQuery(optionalItemsDataCache.value, keywords))]
}

/**
 * @description: 可选项目表格操作
 * @param {string} code
 * @return {*}
 */
const onOptionalItemsCellOperation = (code: string, row: AddItemGroupList) => {
  if (code === 'append' && transfeController) {
    transfeController.rtl([row])
    updataLeftData()
    updataRightData()
  }
}

/**
 * @description: 已选项目组合表格操作
 * @param {string} code
 * @return {*}
 */
const onSelectedItemsCellOperation = (code: string, row: AddItemGroupList) => {
  if (code === 'deletet' && transfeController) {
    transfeController.ltr([row])
    updataLeftData()
    updataRightData()
  }
}

//关闭
const onClose = () => {
  emits('close')
}

// 确认按钮
const onConfirm = () => {
  // 取出id集合
  const ids = selectedItemsDataCache.value.map((item) => {
    return item.id
  })
  // 如果有体检登记id和后端交互
  if (props.checkupRegisterId) {
    saveAddItemGroup({checkupRegisterId: props.checkupRegisterId, situation: props.situation ? Situation.OUTER : Situation.INNER}, ids).then(() => {
      ElMessage.success('保存成功!')
      emits('confirm')
      emits('refresh')
    })
  } else {
    // 如果初次登记，没有体检id,项目组合列表暂存在前端
    emits('confirm', selectedItemsDataCache.value)
  }
}

/**
 * @description: 获取项目组合数据
 * @return {*}
 */
const getAdditions = () => {
  showOptionalItemsLoading.value = true
  const params: GetAddItemGroup = {
    packageId: props.packageId
  }
  // 如果有体检登记id就带上
  props.checkupRegisterId && (params.checkupRegisterId = props.checkupRegisterId)
  getAddItemGroup(params)
    .then((res) => {
      const {data} = res.data || []
      clearData()
      if (transfeController) {
        // 可选项目组合，过滤掉了已选项目组合
        const optionData = data.filter((item) => {
          return props.selectedItemList.findIndex((packageItem) => {
            return item.itemGroupCode === packageItem.itemGroupCode
          }) === -1
            ? true
            : false
        })
        transfeController.changeRightData(optionData)
        updataRightData()
      }
    })
    .catch((err) => {
      console.warn(err)
    })
    .finally(() => {
      showOptionalItemsLoading.value = false
    })
}

// 显示加载状态
const showSaveLoading = ref(false)

onBeforeMount(() => {
  transfeController = new TransferController([], [], {}, {}, 'id', 'id', false, false, ['itemGroupCode', 'itemGroupName'], ['itemGroupCode', 'itemGroupName'])
  getAdditions()
})
</script>

<template>
  <d-dialog
    title="体检加项"
    :show-dialog="showDialog"
    :show-save-loading="showSaveLoading"
    :width="1100"
    @cancel="onClose"
    @confirm="onConfirm"
    @close="onClose"
  >
    <div class="items-row d-common-flex-row d-common-width-full">
      <d-table-promote
        :label-width="100"
        :show-header="true"
        :show-footer="false"
        :stripe="true"
        :table-data="selectedItemsData"
        :search-buttons="selectedItemsSearchButtons"
        :table-header-data="selectedItemsTableHeaderData"
        :row-class-name="tableRowClassName"
        search-from-justify="flexStart"
        :show-loading="showSelectedItemsLoading"
        @form-submit="selectedItemsSubmit"
      >
        <template #oper="scope">
          <operation :row="scope.row" :col="scope.item" @opertion-click="onSelectedItemsCellOperation" />
        </template>
      </d-table-promote>
      <div class="items-space" />
      <d-table-promote
        :label-width="100"
        :show-header="true"
        :show-footer="false"
        :stripe="true"
        :table-data="optionalItemsData"
        :table-header-data="optionalItemsTableHeaderData"
        :search-buttons="optionalItemsSearchButtons"
        :row-class-name="tableRowClassName"
        search-from-justify="flexStart"
        :show-loading="showOptionalItemsLoading"
        @form-submit="optionalItemsSubmit"
      >
        <template #oper="scope">
          <operation :row="scope.row" :col="scope.item" @opertion-click="onOptionalItemsCellOperation" />
        </template>
      </d-table-promote>
    </div>
  </d-dialog>
</template>
<style scoped lang="less">
.items-row {
  height: 700px;
  column-gap: var(--d-margin-level-3);
}
.items-space {
  background: var(--d-color-grey-1);
  height: 100%;
  width: 6px;
}
:deep(.disabled-row) {
  td {
    color: rgba(153, 153, 153, 0.7);
  }
}
</style>
